package com.cloud.controller;



import com.cloud.common.result.Result;
import com.cloud.common.result.ResultCode;
import com.cloud.lb.MyLoadBalancer;
import com.cloud.model.entity.Payment;
import com.cloud.model.form.PaymentForm;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * 使用自定义轮询规则
 * 重点使用 RestClientConfig 中 注释 @LoadBalanced 的 restTemplate2
 */
@RestController
@RequestMapping("/consumer2")
public class OrderLBController {
    @Resource(name="restTemplate2")
    private RestTemplate restTemplate2;

    // 注入自定义的负载均衡规则
    @Resource
    private MyLoadBalancer myLoadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * @author lixiaolong
     * @date 2020/12/23 10:27
     * @description 测试自定义的负载均衡规则
     *
     * 需要关闭默认负载均衡  注释RestClientConfig 的 @LoadBalanced
     */
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        instances.forEach(instance -> {
            System.out.println("InstanceId:"+instance.getInstanceId() + " ServiceId:"+instance.getServiceId() + " Host:" + instance.getHost() + " Port:" + instance.getPort() + " Uri:" + instance.getUri());
        });

        if (instances == null || instances.isEmpty()) {
            return null;
        }
        // 调用自定义的负载均衡策略
        ServiceInstance serviceInstance = myLoadBalancer.instances(instances);
        return restTemplate2.getForObject(serviceInstance.getUri() + "/payment/lb", String.class);

    }

}
